from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from web.form.account import RegisterModelForm, SendSmsForm, logininSMSForm, logininForm
from sass import settings
from web import models
from django.db.models import Q
import uuid
import datetime

"""短信登录"""


def login_sms(request):
    if request.method == 'GET':
        form = logininSMSForm()
        return render(request, 'web/login_sms.html', {'form': form})
    form = logininSMSForm(request.POST)
    if form.is_valid():
        phone = form.cleaned_data['phone']

        user_object = models.User.objects.filter(phone=phone).first()
        # 将用户信息放入seesion
        request.session['user_id'] = user_object.id
        request.session['user_username'] = user_object.username
        request.session.set_expiry(60 * 60 * 24 * 14)

        # 用户输入正确，登录成功
        return HttpResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


"""注册"""


def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'web/register.html', {'form': form})
    form = RegisterModelForm(request,data=request.POST)
    # print(request.POST)
    if form.is_valid():
        # instance = models.User.objects.create(**from.clean_data)相当于下面
        instance = form.save()
        # 创建交易记录

        policy_object = models.PricePolicy.objects.filter( category=1,title="个人免费版").first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )
        print("已经存入数据库")

        return JsonResponse({'status': True, 'data': '/login/'})
        # print(form.cleaned_data)
    return JsonResponse({'status': True, 'error': form.errors})


"""发送短信"""


def send_sms(request):
    # mobile_phone = request.GET.get('mobile_phone')
    # tql = request.GET.get('tql')
    # template_id = settings.TENCENT_SMS_TEMPLATE('tql')
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


"""用户名和密码登录"""


def login(request):
    if request.method == 'GET':
        form = logininForm(request)
        return render(request, 'web/login.html', {'form': form})
    form = logininForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        # user_object = models.User.objects.filter(username=username,password=password).first()
        # （手机=手机 and 密码=密码） 或者 （邮箱=邮箱 and 密码=密码）
        user_object = models.User.objects.filter(Q(email=username) | Q(phone=username)).filter(
            password=password).first()

        if user_object:
            request.session['user_id'] = user_object.id
            request.session['user_username'] = user_object.username
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('web_index')
        form.add_error('username', '用户名或者密码错误')
    return render(request, 'web/login.html', {'form': form})


"""图片验证码"""


def image_code(request):
    from utils.image_code import check_code
    image_object, code = check_code()
    request.session['image_code'] = code
    # 改过期时间
    request.session.set_expiry(60 * 60)
    # 把图片的内容写到内存 stream
    from io import BytesIO
    stream = BytesIO()
    image_object.save(stream, 'png')
    # 获取到图片内容
    stream.getvalue()
    return HttpResponse(stream.getvalue())


"""用户退出"""


def loginout(request):
    request.session.flush()
    return redirect('web_index')



